<template>
    <div>
        <!--        面包屑导航-->
        <breadcrumb @onNavClick="onNavClickStr" :navData="navData"></breadcrumb>
        <!--        卡片区域-->
        <el-card class="box-card">
            <!--            搜索和添加-->
            <el-row :gutter="20">
                <el-col :span="10">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" class="input-with-select">
                        <el-button @click="searchUser" slot="append" icon="el-icon-search"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addUserVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!--用户列表-->
            <el-table
                :data="tableData"
                border
                style="width: 100%">
                <el-table-column label="#" type="index"></el-table-column>
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column prop="role_name" label="角色"></el-table-column>
                <el-table-column prop="mg_state" label="状态">
                    <template slot-scope="scope">
                        <el-switch @change="onStateChange(scope.row)" v-model="scope.row.mg_state"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="date" label="操作">
                    <template slot-scope="scope">
                        <!--                        修改-->
                        <el-button type="primary" size="mini" @click="editUser(scope.row)" icon="el-icon-edit"></el-button>
                        <!--                        删除-->
                        <el-button type="danger" size="mini" @click=onDeleteUser(scope.row) icon="el-icon-delete"></el-button>
                        <!--                        分配权限-->
                        <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
                            <el-button @click="assignRoles(scope.row)" type="warning" size="mini" icon="el-icon-setting"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!--            分页-->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[1, 2, 5, 10]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>

        </el-card>



<!--        添加用户-->
        <el-dialog title="添加用户" :visible.sync="addUserVisible">
            <el-form :model="addUser" :rules="addUserRules" ref="addUserRuleForm" label-width="100px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addUser.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addUser.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addUser.email"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                    <el-input v-model="addUser.mobile"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addUserVisible = false">取 消</el-button>
                <el-button type="primary" @click="onAddUser">确 定</el-button>
            </div>
        </el-dialog>
        <!--修改用户对话框-->
        <el-dialog
            title="编辑用户"
            :visible.sync="editDialogVisible"
            width="60%">
            <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
                <!--用户名-->
                <el-form-item label="用户名">
                    <el-input disabled v-model="editForm.username"></el-input>
                </el-form-item>
                <!--邮箱-->
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <!--电话-->
                <el-form-item label="电话" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible= false">取 消</el-button>
                <el-button type="primary" @click="onEditBtnClick">确 定</el-button>
            </span>
        </el-dialog>
        <!--分配角色对话框-->
        <el-dialog
            title="分配角色"
            :visible.sync="rolesDialogVisible"
            width="60%">
            <el-form :model="rolesForm" ref="rolesFormRef" label-width="100px">
                <!--用户名-->
                <el-form-item label="当前的用户:">
                    <span>{{rolesForm.username}}</span>
                    <!--<el-input disabled v-model="rolesForm.username"></el-input>-->
                </el-form-item>
                <!--角色-->
                <el-form-item label="当前的角色:">
                    <span>{{rolesForm.role_name}}</span>
                    <!--<el-input v-model="rolesForm.role_name"></el-input>-->
                </el-form-item>
                <!--新角色-->
                <el-form-item label="分配新角色:">
                    <el-select v-model="rolesForm.rid" placeholder="请选择">
                        <el-option
                            v-for="item in rolesOptions"
                            :key="item.id"
                            :label="item.roleName"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="rolesDialogVisible= false">取 消</el-button>
                <el-button type="primary" @click="onAssignRolesBtnClick">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import loginAPI from "../../http/loginAPI";

export default {
    /*beforeCreate() {
        this.$bus.$on("onNavClick123",function (str){
            console.log(str+"哈哈==>beforeCreate");
        })
    },*/
    created() {
        // this.$bus.$on("onNavClick123",this.onNavClick123)
        this.getUserList()
    },
    name: "Users",
    data() {
        //rule 当前验证规则
        //value 当前如果的内容
        //callback 成功或失败后的回调函数
        let checkEmail = async (rule, value, callback) => {
            //邮箱规则
            let reg = /^[0-9|A-z|_]{1,17}[@][0-9|A-z]{1,3}.(com)$/;
            //如果通过验证 直接调用callback方法
            if(reg.test(value)){
                return callback();
            }else {
                //如果未通过验证 则返回错误信息
                return callback(new Error('请输入正确的邮箱'));
            }


            //所有的文档代码中,如果存在setTimeout语法,一般认为是模拟异步操作,在真实项目中如果使用的话一般用接口请求去替代
           /* //验证用户名是否被占用
            let {data:res} = await this.$http.post("checkUserName", {name: value})
            if(res.meta.code !== 200){
                return callback(new Error('当前用户名已经被占用,请重新输入'));
            }else {
                return callback();
            }*/
        };
        let checkMobile = (rule, value, callback) => {
            //电话规则
            let reg = /^1[3|4|5|7|8][0-9]{9}$/;
            //如果通过验证 直接调用callback方法
            if(reg.test(value)){
                return callback();
            }else {
                //如果未通过验证 则返回错误信息
                return callback(new Error('请输入正确的电话号码'));
            }
        };


        return {
            //查询用户信息的参数
            queryInfo: {
                //查询条件
                query: "",
                //当前页
                pagenum: 1,
                //每页显示条数
                pagesize: 10,
            },
            //总条数
            total:0,
            navData: [
                "用户管理",
                "用户列表"
            ],
            tableData: [],
            //显示隐藏添加用户对话框
            addUserVisible: false,
            //添加用户表单
            addUser:{
                username: "",
                password: "",
                email: "",
                mobile: ""
            },
            //添加用户表单验证
            addUserRules: {
                username: [
                    //required必填  trigger(触发规则) 失去焦点
                    { required: true, message: '请输入用户名称', trigger: 'blur' },
                    { min: 5, max: 8, message: '长度在 5 到 8 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 5, max: 8, message: '长度在 5 到 8 个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入电话', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ],
            },
            editDialogVisible: false,
            //编辑用户表单
            editForm: {
                username: "",
                email: "",
                mobile: ""
            },
            editRules: {
                email: [
                    {required: true, message: '请输入邮箱', trigger: 'blur'},
                    {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
                ],
                mobile: [
                    {required: true, message: '请输入电话号码', trigger: 'blur'},
                    {validator: checkMobile, message: '请输入正确的电话号码', trigger: 'blur'}
                ],
            },
            curEditId: "",
            //分配角色
            rolesDialogVisible: false,////分配角色对话框显示隐藏
            rolesForm:{
                userId:"",//当前用户id
                username:"",//当前的用户
                role_name:"",//当前的角色
                rid:"",//新的角色ID
            },
            rolesOptions:[]
        }
    },
    methods: {
        onNavClickStr(str) {
            console.log(str);
        },
        /*onNavClick123(str){
            console.log(str+"哈哈");
        },*/
        //获取用户列表
        async getUserList(){
            let {data:res} = await this.$http.get("users", {
                params: this.queryInfo
            })
            if(res.meta.status !== 200) return this.$message.error(res.meta.msg);
            this.total = res.data.total;
            this.tableData = res.data.users;
            console.log(res)

        },
        //查询用户信息
        searchUser(){
            this.queryInfo.pagenum = 1;
            this.getUserList();
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.queryInfo.pagesize = val;
            this.getUserList();
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.queryInfo.pagenum = val;
            this.getUserList();
        },
        //切换用户状态
        async onStateChange(row){
            console.log("切换用户状态",row);
            //发送请求状态改变的数据
            let {data:res} = await this.$http.put(`users/${row.id}/state/${row.mg_state}`);
            //如果返回状态异常 则重写赋值为初始状态
            if(res.meta.status !== 200){
                row.mg_state = !row.mg_state;
                return this.$message.error(res.meta.msg);
            }
            this.$message.success(res.meta.msg);
        },
        //确定添加用户
        onAddUser(){
            this.$refs.addUserRuleForm.validate(async (valid)=>{
                //如果valid为true 则表示整个表单内的校验都通过了
                if(!valid) return;
                //通过校验
                let {data:res} = await this.$http.post("users",this.addUser);
                if(res.meta.status !== 201) return this.$message.error(res.meta.msg);
                this.getUserList()
                this.$message.success(res.meta.msg);
                this.addUserVisible = false;
            })
        },
        //删除用户
        async onDeleteUser(row){
            let result = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err=>err);
            console.log(result);
            if(result !== "confirm") return this.$message.info("取消删除")
            //用户确定要删除操作
            let {data:res} = await this.$http.delete(`users/${row.id}`)
            if(res.meta.status !== 200) return this.$message.error(res.meta.msg);
            this.getUserList()
            this.$message.success(res.meta.msg);
        },
        //编辑用户
        editUser(item) {
            console.log("编辑用户===>", item);
            this.curEditId = item.id;
            this.editForm.username = item.username;
            this.editForm.email = item.email;
            this.editForm.mobile = item.mobile;
            this.editDialogVisible = true;
        },
        //点击确定修改
        onEditBtnClick() {
            this.$refs.editFormRef.validate((value) => {
                if (!value) return;
                this.$http.put(`users/${this.curEditId}`, this.editForm).then((res) => {
                    console.log("提交后的数据===>", res.data);
                    let data = res.data;
                    if (data.meta.status === 200) {
                        //重新获取数据
                        this.getUserList();
                        this.$message.success(data.meta.msg);
                        this.editDialogVisible = false;
                    } else {//提示错误信息
                        this.$message.error(data.meta.msg);
                    }
                })

            })
        },
        //分配角色
        assignRoles(item){
            console.log("分配角色===>", item);
            this.rolesForm.userId = item.id;
            this.rolesForm.username = item.username;
            this.rolesForm.role_name = item.role_name;
            this.rolesForm.rid = "";
            this.$http.get("roles").then((res)=>{
                console.log(res.data);
                this.rolesOptions = res.data.data;
                this.rolesDialogVisible = true;
            });
        },
        onAssignRolesBtnClick(){
            let rid = this.rolesForm.rid;
            if(!rid){
                return this.$message.warning("请选择要分配的新角色！")
            }
            this.$http.put(`users/${this.rolesForm.userId}/role`, {rid}).then((res) => {
                console.log("提交后的数据===>", res.data);
                let data = res.data;
                if (data.meta.status === 200) {
                    //重新获取数据
                    this.getUserList();
                    this.$message.success(data.meta.msg);
                    this.rolesDialogVisible = false;
                } else {//提示错误信息
                    this.$message.error(data.meta.msg);
                }
            })
        }
    }
}
</script>

<style scoped>

</style>